package com.un.ebs.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.un.ebs.core.config.OSSConfig;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.OSSUtil;
import com.un.ebs.product.domain.ProductImage;
import com.un.ebs.product.domain.ProductPack;
import com.un.ebs.product.domain.ProductPackImage;
import com.un.ebs.product.domain.ProductPackItem;
import com.un.ebs.product.mapper.ProductPackImageMapper;
import com.un.ebs.product.mapper.ProductPackItemMapper;
import com.un.ebs.product.mapper.ProductPackMapper;
import com.un.ebs.product.service.ProductPackService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.un.ebs.product.dto.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liubo
 * @since 2019-11-09
 */
@Service
public class ProductPackServiceImpl extends ServiceImpl<ProductPackMapper, ProductPack> implements ProductPackService {

    @Autowired
    private ProductPackItemMapper productPackItemMapper;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private ProductPackImageMapper productPackImageMapper;

    @Transactional
    @Override
    public void add(ProductPackAddDto req) {
        ProductPack obj = new ProductPack();
        obj.setName(req.getName());
        obj.setPrice(req.getPrice());
        obj.setRemark(req.getRemark());
        obj.setIsDelete(false);
        obj.setIsSale(false);
        obj.insert();

        for (ProductPackItemDto itemDto:req.getItems()) {
            ProductPackItem item = new ProductPackItem();
            item.setPackId(obj.getId());
            item.setSkuId(itemDto.getSkuId());
            item.setPrice(itemDto.getPrice());
            item.setQty(itemDto.getQty());
            item.insert();
        }
    }

    @Transactional
    @Override
    public void update(ProductPackUpdateDto req) {
        ProductPack obj = getById(req.getId());
        obj.setName(req.getName());
        obj.setPrice(req.getPrice());
        obj.setRemark(req.getRemark());
        obj.updateById();

        List<String> ids = req.getItems().stream().map(s->s.getId()).collect(Collectors.toList());
        List<ProductPackItem> items = productPackItemMapper.selectBatchIds(ids);
        for (ProductPackItemDto itemDto:req.getItems()) {
            Optional<ProductPackItem> item = items.stream().filter(s->s.getId().equals(itemDto.getId())).findFirst();
            if(!item.isPresent()) continue;

            item.get().setSkuId(itemDto.getSkuId());
            item.get().setPrice(itemDto.getPrice());
            item.get().setQty(itemDto.getQty());
            item.get().updateById();
        }
    }

    @Override
    public String uploadImage(MultipartFile file, String packId) {
        if(com.un.ebs.core.util.StringUtils.isNullOrEmpty(packId)){
            throw new BusinessException("packId 不能为空。");
        }

        //String url = OSSUtil.upload(ossConfig,file,String.format("packId/%s",packId));
        String url = OSSUtil.upload(file,String.format("packId/%s",packId));
        if(com.un.ebs.core.util.StringUtils.isNullOrEmpty(url)){
            return null;
        }

        try{
            ProductPackImage img = new ProductPackImage();
            img.setImgUrl(url);
            img.setPackId(packId);
            img.setSort(productPackImageMapper.maxSort(packId));
            img.insert();
        }catch (Exception e){
            //OSSUtil.delete(ossConfig,url);
            OSSUtil.delete(url);
            throw new BusinessException("上传失败：" + e.getMessage());
        }
        return url;
    }

    @Override
    public void deleteImage(String id) {
        ProductPackImage image = productPackImageMapper.selectById(id);
        if(image==null){
            throw new BusinessEntityNotFoundException(id,"product_pack_image");
        }

        //OSSUtil.delete(ossConfig,image.getImgUrl());
        OSSUtil.delete(image.getImgUrl());
        image.deleteById();
    }

    @Transactional
    @Override
    public void deleteImageByPackId(String packId) {
        LambdaQueryWrapper<ProductPackImage> lq = Wrappers.lambdaQuery();
        lq.eq(ProductPackImage::getPackId,packId);
        List<ProductPackImage> images = productPackImageMapper.selectList(lq);
        for (ProductPackImage image:images) {
            //OSSUtil.delete(ossConfig,image.getImgUrl());
            OSSUtil.delete(image.getImgUrl());
            image.deleteById();
        }
    }

    @Override
    public ProductPack queryById(String id) {
        return getBaseMapper().selectById(id);
    }

    @Override
    public void delete(String id){
        getBaseMapper().deleteById(id);
    }

}